package com.reebake.ideal.desensitize.properties;

import com.reebake.ideal.desensitize.enums.DesensitizeType;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.LinkedHashMap;
import java.util.Map;

@Data
@ConfigurationProperties(prefix = "desensitize")
public class DesensitizeProperties implements InitializingBean {
    private static final Map<String, DesensitizeRule> defaultRules = new LinkedHashMap<>();

    static {
        defaultRules.put(DesensitizeType.MOBILE_PHONE.name(), new DesensitizeRule("(1\\d{2})\\d{4}(\\d{4})", "$1****$2"));
        defaultRules.put(DesensitizeType.CHINESE_NAME.name(), new DesensitizeRule("([\u4e00-\u9fa5\\s])([\u4e00-\u9fa5.\\s]*)", "$1**"));
        defaultRules.put(DesensitizeType.ID_NO.name(), new DesensitizeRule("(.{6})(?:\\d+)(.{4})", "$1**********$2"));
        defaultRules.put(DesensitizeType.EMAIL.name(), new DesensitizeRule("([a-zA-Z0-9_\\-.]{1,3})[a-zA-Z0-9_\\-.]*@([a-zA-Z0-9_\\-.]+)\\.([a-zA-Z]{2,5})", "$1***@$2.$3"));
        defaultRules.put(DesensitizeType.IP.name(), new DesensitizeRule("(\\d{1,3}\\.){3}\\d{1,3}", "$1***"));
        defaultRules.put(DesensitizeType.PHONE.name(), new DesensitizeRule("(0\\d{2,3}-?)\\d{4}(\\d{3,4})", "$1****$2"));
        defaultRules.put(DesensitizeType.VLP_NO.name(), new DesensitizeRule("^(.\\w{0,1})\\w{1,4}(.)", "$1****"));
        defaultRules.put(DesensitizeType.ADDRESS.name(), new DesensitizeRule("(.*[省|自治区])?(.*[市|盟|自治州])?(.*[区|县|旗])(.*)", "$1$2$3***********"));
        defaultRules.put(DesensitizeType.USCI.name(), new DesensitizeRule("(\\w{5}).*(\\w{5})", "$1********$2"));
        defaultRules.put(DesensitizeType.BANK_ACCOUNT.name(), new DesensitizeRule("(?<=\\d{6})\\d+(?=\\d{4})", "*********"));
        defaultRules.put(DesensitizeType.AUTO.name(), new DesensitizeRule("(\\w{4}).*", "$1********"));
    }

    private Map<String, DesensitizeRule> rules = new LinkedHashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        for (Map.Entry<String, DesensitizeRule> entry : defaultRules.entrySet()) {
            rules.putIfAbsent(entry.getKey(), entry.getValue());
        }
    }

    @Data
    public static class DesensitizeRule {
        /**
         * 正则表达式
         */
        private String regex;
        /**
         * 替换字符串
         */
        private String replacement;

        public DesensitizeRule(){

        }

        public  DesensitizeRule(String regex, String replacement){
            this.regex = regex;
            this.replacement = replacement;
        }
    }
}
